package com.example.w.config;

import com.example.w.common.filter.ShiroUerFilter;
import com.example.w.common.realm.CustomerRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager manager) {
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        factoryBean.setSecurityManager(manager);

        Map<String, String> filterChainDefMap = new HashMap<>();
        //放行swagger
        filterChainDefMap.put("/swagger-ui.html","anon");
        filterChainDefMap.put("/swagger/**","anon");
        filterChainDefMap.put("/webjars/**", "anon");
        filterChainDefMap.put("/swagger-resources/**","anon");
        filterChainDefMap.put("/v2/**","anon");
        filterChainDefMap.put("/static/**", "anon");
        //开放登录和注册接口
        filterChainDefMap.put("/user/login", "anon");
        filterChainDefMap.put("/user/register", "anon");
        //控制所有页面权限和认证
        //filterChainDefMap.put("/**", "authc");
        filterChainDefMap.put("/**", "anon");

        factoryBean.setFilterChainDefinitionMap(filterChainDefMap);
        factoryBean.getFilters().put("authc", new ShiroUerFilter());

        return factoryBean;
    }

    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("getRealm") Realm realm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(realm);
        return securityManager;
    }
    
    @Bean
    public Realm getRealm() {
        CustomerRealm customerRealm = new CustomerRealm();
        //创建加密凭证匹配器，指定加密算法
        HashedCredentialsMatcher md5 = new HashedCredentialsMatcher("md5");
        //设置散列次数
        md5.setHashIterations(1024);
        //设置匹配器
        customerRealm.setCredentialsMatcher(md5);
        return customerRealm;
    }
}
